package com.multi.framework.init;

import com.baomidou.dynamic.datasource.processor.DsProcessor;
import com.multi.common.constant.SourceConstant;
import com.multi.common.utils.StringUtils;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 从请求头中获取租户Id信息
 * @ClassName DsHeaderProcessor
 * @Author pzj
 * @Data 2024/12/3 14:59
 */
@Primary
@Component
public class DsHeaderProcessor extends DsProcessor {
    /**
     * header prefix
     */
    private static final String HEADER_PREFIX = "#header";

    @Override
    public boolean matches(String key) {
        return key.startsWith(HEADER_PREFIX);
    }

    @Override
    public String doDetermineDatasource(MethodInvocation invocation, String key) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String header = request.getHeader(key.substring(8));
        if(StringUtils.isEmpty(header)){
            header = (String) request.getAttribute(SourceConstant.TENANT_ID);
        }
        return header;
    }
}
